<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, minimal-ui" />
        
        <script src="../../js/greyspots.js" type="text/javascript"></script>
        <link href="../../css/greyspots.css" type="text/css" rel="stylesheet" />
        
        <link href="../../css/postage.css" type="text/css" rel="stylesheet" />
        <script src="datagrid.js" type="text/javascript"></script>
        <link href="datagrid.css" type="text/css" rel="stylesheet" />
        <script src="../../js/page-zoom.js" type="text/javascript"></script>

        
        <script>
            //global GS, window, ml
            //jslint browser:true, white:true, multivar:true, for:true
            var bolCurl = false;
            function toggleUpdate() {
                if (document.getElementById('tableElement').hasAttribute('update-dialog') === true) {
                    document.getElementById('tableElement').removeAttribute('update-dialog');
                } else {
                    document.getElementById('tableElement').setAttribute('update-dialog', 'show');
                }
                document.getElementById('tableElement').render();
                document.getElementById('tableElement').refresh();
            }
            
            function checkDisableds() {
                var elems = document.getElementsByClassName('navBtns');
                var action;
                var intCurrentRecord = (
                        document.getElementById('tableElement').internalSelection.originRecord || 0
                    );
                for (i = 0, len = elems.length; i < len; i += 1) {
                    
                    var intNavRecord = (
                        document.getElementById('tableElement').internalSelection.originRecord || 0
                    );
                    var intMaxRecord = (
                        document.getElementById('tableElement').internalData.records.length - 1
                    );
                    action = elems[i].getAttribute('increment');
                    
                    if (action === 'first') {
                        intNavRecord = 0;
                    } else if (action === 'previous') {
                        intNavRecord -= 1;
                    } else if (action === 'next') {
                        intNavRecord += 1;
                    } else if (action === 'plusten') {
                        intNavRecord += 10;
                    } else if (action === 'minusten') {
                        intNavRecord -= 10;
                    } else if (action === 'last') {
                        intNavRecord = intMaxRecord;
                    } else if (typeof action === 'number') {
                        intNavRecord = action - 1;
                    } else {
                        intNavRecord = parseInt(action, 10) - 1;
                    }
                    
                    if (intNavRecord < 0 || (intCurrentRecord === 0 && (action === 'first' || action === 'previous' || action === 'minusten'))) {
                        elems[i].setAttribute('disabled', '');
                    } else if (intNavRecord > intMaxRecord || (intCurrentRecord === intMaxRecord && (action === 'next' || action === 'plusten' || action === 'last'))) {
                        elems[i].setAttribute('disabled', '');
                    } else {
                        if (elems[i].hasAttribute('disabled'))  {
                            elems[i].removeAttribute('disabled');
                        }
                    }

                    //console.log(intCurrentRecord, intNavRecord, intMaxRecord, elems[i]);
                }
            }
            
            function quote_ident(strName) {
                'use strict';
                var bolQuote = !Boolean(strName.match(/^[a-z_]{1,}[a-z_0-9]*$/));
                
                //_ is safe
                //0-9 is safe (except when first char)
                //a-z is safe
                
                // if we need to quote: double up double quotes
                if (bolQuote) {
                    return '"' + strName.replace(/\"/g, '""') + '"';
                }
                
                return strName;
            }
            
            window.addEventListener('load', function () {
                'use strict'
                var qs = GS.qryToJSON(GS.getQueryString()), strQuery;
                console.log(qs);
                zoomStart();

                GS.addLoader('getting_info');
                // get pk if possible (else use whole column list)
                strQuery = ml(function () {/*
                    SELECT  (
                                 SELECT array_to_string(array_agg(attname), ',')
                                   FROM pg_constraint con
                              LEFT JOIN pg_attribute att ON att.attnum = con.conkey[1] AND att.attrelid = con.conrelid
                                  WHERE con.contype = 'p' AND con.conrelid = getoid.oid
                               GROUP BY attnum
                               ORDER BY attnum ASC
                            ),
                            (
                                 SELECT array_to_string(array_agg(attname), ',')
                                   FROM pg_attribute
                                  WHERE pg_attribute.attisdropped IS FALSE AND pg_attribute.attnum > 0 AND attrelid = getoid.oid
                            ),
                            (
                                SELECT array_to_string(array_agg(default_expression), ',')
                                  FROM (         SELECT pg_catalog.pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS default_expression
                                                   FROM pg_constraint con
                                              LEFT JOIN pg_attribute att ON att.attnum = con.conkey[1] AND att.attrelid = con.conrelid
                                        LEFT OUTER JOIN pg_attrdef ON adrelid = attrelid AND adnum = attnum
                                                  WHERE attrelid = getoid.oid
                                                  ORDER BY attnum ASC) em
                            )
                      FROM pg_class getoid
                 LEFT JOIN pg_namespace pg_schema ON pg_schema.oid = getoid.relnamespace
                     WHERE pg_schema.nspname = $SAFEqUoTE${{NSPNAME}}$SAFEqUoTE$ AND getoid.relname = $SAFEqUoTE${{STRNAME}}$SAFEqUoTE$
                */}).replace(/\{\{NSPNAME\}\}/gim, qs.schema)
                    .replace(/\{\{STRNAME\}\}/gim, qs.object);
                
                    
                var tableElement = document.createElement('gs-table');
                GS.requestRawFromSocket(GS.envSocket, strQuery, function (data, error) {
                    var arrColumns, strPK, strColumns, strSequenceDefaults, arrSequenceDefaults, i, len, strHTML, arrColumns, strLock;
                    
                    if (!error) {
                        if (data.intCallbackNumber === 0) {
                            arrColumns = data.strMessage.split('\t');
                            //console.log(arrColumns);
                            strPK = GS.decodeFromTabDelimited(arrColumns[0]);
                            
                            strSequenceDefaults = GS.decodeFromTabDelimited(arrColumns[2] || '');
                            arrSequenceDefaults = strSequenceDefaults.split(',');
                            
                            if (arrColumns[1]) {
                                strColumns = GS.decodeFromTabDelimited(arrColumns[1]);
                                arrColumns = strColumns.split(',');
                            }
                            
                            tableElement.setAttribute('all-cols', strColumns);
                            tableElement.setAttribute('cols', strColumns);
                            tableElement.setAttribute('id', 'tableElement');
                            tableElement.setAttribute('null-string', 'NULL');
                            tableElement.setAttribute('style', 'width: 100%; height: 100%;');
                            tableElement.setAttribute('focus-on-load', '');
                            tableElement.setAttribute('src', (qs.schema + '.' + qs.object) || '');
                            
                    // <template for="update-dialog">
                            
                            var updateContent = ''
                            var headerContent = '';
                            var recordContent = '';
                            var copyContent = '';
                            var insertContent = '';
                            for (i = 0, len = arrColumns.length; i < len; i += 1) {
                                updateContent += '<label>' + arrColumns[i] + '</label>\n';
                                updateContent += '<gs-text column="' + arrColumns[i] + '"></gs-text>\n';
                                headerContent += '<gs-cell>' + arrColumns[i] + '</gs-cell>\n';
                                recordContent += '<gs-cell header="' + arrColumns[i] + '"><label><input column="' + arrColumns[i] + '" /></label></gs-cell>\n';
                                copyContent += '<gs-cell header="' + arrColumns[i] + '">{{= row[' + JSON.stringify(arrColumns[i]) + '] }}</gs-cell>\n';
                                insertContent += '<gs-cell header="' + arrColumns[i] + '"><label><input column="' + arrColumns[i] + '" /></label></gs-cell>\n';
                            }
                            
                            tableElement.innerHTML = ml(function () {/*
    <template for="top-hud">
        <gs-button onclick="document.getElementById('tableElement').deleteSelected();" inline no-focus icononly icon="times">&nbsp;</gs-button>
        <gs-button onclick="document.getElementById('tableElement').refresh();" inline no-focus icononly icon="refresh">&nbsp;</gs-button>
        <gs-button onclick="document.getElementById('tableElement').openPrefs(this);" inline no-focus icononly icon="sliders">&nbsp;</gs-button>
        <gs-button onclick="document.getElementById('tableElement').toggleFullscreen(this);" inline no-focus icononly icon="expand">&nbsp;</gs-button>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <gs-button onclick="document.getElementById('tableElement').sort('asc');" inline no-focus iconleft icon="sort-alpha-asc">Sort A to Z</gs-button>
        <gs-button onclick="document.getElementById('tableElement').sort('desc');" inline no-focus iconleft icon="sort-alpha-desc">Sort Z to A</gs-button>
        <gs-button onclick="document.getElementById('tableElement').sort('clear');" inline no-focus iconleft icon="trash">Clear Sort</gs-button>
        <gs-button onclick="document.getElementById('tableElement').clearFilter();" inline no-focus iconleft icon="trash">Clear Filter</gs-button>
        <gs-button onclick="toggleUpdate();" inline no-focus>Multi-update</gs-button>
        
        <gs-button onclick="document.getElementById('tableElement').resizeAllColumns()" inline no-focus
                    title="Resize all columns to fit their content. The new widths will be based on the content of the visible cells.">
            AutoFit
        </gs-button>
    </template>
    <template for="bottom-hud">
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('first'); checkDisableds();" increment="first" class="navBtns" icon="step-backward">&nbsp;</gs-button>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('minusten'); checkDisableds();" increment="minusten" class="navBtns" icon="backward">&nbsp;</gs-button>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('previous'); checkDisableds();" increment="previous" class="navBtns" icon="caret-left">&nbsp;</gs-button>
        <gs-current-record inline for="tableElement"></gs-current-record>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('next'); checkDisableds();" increment="next" class="navBtns" icon="caret-right">&nbsp;</gs-button>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('plusten'); checkDisableds();" increment="plusten" class="navBtns" icon="forward">&nbsp;</gs-button>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('last'); checkDisableds();" increment="last" class="navBtns" icon="step-forward">&nbsp;</gs-button>
        <gs-button inline no-focus icononly onclick="document.getElementById('tableElement').goToLine('insert'); checkDisableds();" increment="insert" class="navBtns" icon="plus"></gs-button>
    </template>
    <template for="header-record">
        {{HEADERTOKEN}}
    </template>
    <template for="data-record">
        {{RECORDTOKEN}}
    </template>
    <template for="copy">
        {{COPYTOKEN}}
    </template>
    <template for="insert-record">
        {{INSERTTOKEN}}
    </template>
    <template for="update-dialog">
        {{UPDATETOKEN}}
    </template>
                            */}).replace(/{{HEADERTOKEN}}/gi, headerContent).replace(/{{UPDATETOKEN}}/gi, updateContent).replace(/{{RECORDTOKEN}}/gi, recordContent).replace(/{{COPYTOKEN}}/gi, copyContent).replace(/{{INSERTTOKEN}}/gi, insertContent);



                            if (strPK && strPK !== '\\N') {
                                tableElement.setAttribute('pk', strPK);
                                tableElement.setAttribute('ord', quote_ident(strPK) + ' DESC');
                                
                                for (i = 0, len = arrSequenceDefaults.length; i < len; i += 1) {
                                    if (arrSequenceDefaults[i].indexOf('nextval') > -1) {
                                        arrSequenceDefaults[i] =
                                                arrSequenceDefaults[i]
                                                        .substring(arrSequenceDefaults[i].indexOf('\'') + 1,
                                                                   arrSequenceDefaults[i].lastIndexOf('\''))
                                        arrSequenceDefaults[i] = arrSequenceDefaults[i].replace(/''/gi, '\'');
                                        
                                    } else {
                                        arrSequenceDefaults[i] = '';
                                    }
                                }
                                
                                strSequenceDefaults = arrSequenceDefaults.join(',');
                                tableElement.setAttribute('seq', strSequenceDefaults);
                            }
                            if (strColumns) {
                                tableElement.setAttribute('lock', strColumns);
                            }
                            
                            document.getElementById('body').appendChild(tableElement);
                            
                            // bind controls
                            for (i = 0, len = arrColumns.length, strHTML = ''; i < len; i += 1) {
                                strHTML += '<option>' + encodeHTML(arrColumns[i]) + '</option>';
                            }
                            document.getElementById('select-pk').innerHTML = '<option value="PKUNKNOWN">Unknown</option>' + strHTML;
                            document.getElementById('select-pk').value = (tableElement.getAttribute('pk') || 'PKUNKNOWN');
                            document.getElementById('select-pk').addEventListener('change', function () {
                                if (this.value === 'PKUNKNOWN') {
                                    tableElement.removeAttribute('pk');
                                } else {
                                    tableElement.setAttribute('pk', this.value);
                                }
                                
                                tableElement.refresh();
                            });
                            
                            document.getElementById('text-limit').value = (tableElement.getAttribute('limit') || '');
                            document.getElementById('text-limit').addEventListener('change', function () {
                                tableElement.setAttribute('limit', this.value);
                                tableElement.refresh();
                                // checkDisableds();
                            });
                            
                            document.getElementById('text-offset').value = (tableElement.getAttribute('offset') || '');
                            document.getElementById('text-offset').addEventListener('change', function () {
                                tableElement.setAttribute('offset', this.value);
                                tableElement.refresh();
                                // checkDisableds();
                            });
                            
                            document.getElementById('text-where').value = (tableElement.getAttribute('where') || '');
                            document.getElementById('text-where').addEventListener('change', function () {
                                tableElement.setAttribute('where', this.value);
                                tableElement.refresh();
                            });
                            
                            document.getElementById('text-order-by').value = (tableElement.getAttribute('ord') || '');
                            document.getElementById('text-order-by').addEventListener('change', function () {
                                tableElement.setAttribute('ord', this.value);
                                tableElement.refresh();
                            });
                            
                            GS.removeLoader('getting_info');
                            
                            document.getElementById('tableElement').addEventListener('after_select', function () {
                                checkDisableds();
                            });
                            
                            document.getElementById('tableElement').addEventListener('selection_change', function () {
                                checkDisableds();
                                //console.log('test');
                            });
                        }
                        
                    } else {
                        GS.removeLoader('getting_info');
                        GS.webSocketErrorDialog(data);
                    }
                });
                
            });
        </script>
        <style>
            
            #button-column-list,
            #button-paginate-left,
            #button-paginate-right {
                border-color: #006E00;
                border-bottom: 0 none;
            }
            
            #button-column-list {
                
            }
            #button-paginate-left {
                border-right: 0 none;
            }
            #button-paginate-right {
                border-left: 0 none;
            }
            
            label {
                padding: 0.268em;
            }
            gs-cell > label > input {
                width: 100%;
                border: 0 none;
                margin: 0;
                padding: 0;
                font-size: 1em;
                font-family: inherit;
                
                -webkit-appearance: none;
                -moz-appearance: none;
                
                -webkit-border-radius: inherit;
                /*-moz-border-radius: none;*/
            }
            
            gs-current-record[inline] {
                display: inline-block;
            }
            gs-button, gs-checkbox {
                color: #111111;
                margin: 0;
                box-shadow: none !important;
                border: 1px solid #eee;
                line-height: normal;
                padding: 0.5em;
            }
        </style>
        <script src="../../js/settings.js" type="text/javascript"></script>
        <script>
            if (window.parent) {
                window.parent.addEventListener('resize', function () {
                    if (localStorage && localStorage.customCSS && document.getElementById('customCss')) {
                        refreshCustomCSS(localStorage.customCSS);
                    }
                    /*
                    if (localStorage && localStorage.customCSS && document.getElementById('customCss')) {
                        document.getElementById('customCss').innerHTML = localStorage.customCSS;
                    }
                    */
                });
            }
        </script>
        <style id="customCss"></style>
    </head>
    <body>
        <gs-page>
            <gs-body id="body" padded flex-vertical flex-fill>
                <!--
                    visible columns
                -->
                
                <gs-grid reflow-at="455px" widths="1,1">
                    <gs-block>
                        <div flex-horizontal>
                            <label for="select-pk"><b>Primary Key:</b></label>
                            <gs-select id="select-pk" flex></gs-select>
                        </div>
                    </gs-block>
                    <gs-block>
                        <gs-grid reflow-at="200px" widths="1,1">
                            <gs-block>
                                <div flex-horizontal>
                                    <label for="text-limit"><b>LIMIT:</b></label>
                                    <gs-text id="text-limit" flex></gs-text>
                                </div>
                            </gs-block>
                            <gs-block>
                                <div flex-horizontal>
                                    <label for="text-offset"><b>OFFSET:</b></label>
                                    <gs-text id="text-offset" flex></gs-text>
                                </div>
                            </gs-block>
                        </gs-grid>
                    </gs-block>
                </gs-grid>
                
                <gs-grid reflow-at="455px" widths="1,1">
                    <gs-block>
                        <div flex-horizontal>
                            <label for="text-where"><b>WHERE:</b></label>
                            <gs-text id="text-where" flex></gs-text>
                        </div>
                    </gs-block>
                    <gs-block>
                        <div flex-horizontal>
                            <label for="text-order-by"><b>ORDER BY:</b></label>
                            <gs-text id="text-order-by" flex></gs-text>
                        </div>
                    </gs-block>
                </gs-grid>
                
                
            </gs-body>
        </gs-page>
    </body>
</html>